<?php
/**
 * 新建考试项目页面 - 修复版
 * 功能：创建新的考试项目，设置项目名称和时间范围
 * 权限：仅考试项目管理员可访问
 */

// 开启输出缓冲，防止headers already sent错误
ob_start();

// 错误报告设置
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);

// 开启会话
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// 检查用户是否已登录
if (!isset($_SESSION['user_id']) || !isset($_SESSION['username'])) {
    ob_end_clean();
    header('Location: index.php');
    exit();
}

// 为导航栏设置全局变量
$current_user_id = $_SESSION['user_id'] ?? '';
$GLOBALS['current_user_id'] = $current_user_id;

// 数据库连接
try {
    if (!file_exists('database.php')) {
        throw new Exception("database.php文件不存在");
    }

    require_once 'database.php';

    if (!isset($conn) || !($conn instanceof mysqli)) {
        throw new Exception("数据库连接失败");
    }

    if (!$conn->ping()) {
        throw new Exception("数据库连接已断开");
    }

} catch (Exception $e) {
    ob_end_clean();
    $_SESSION['error_message'] = "数据库连接失败：" . $e->getMessage();
    header('Location: user_home.php');
    exit();
}

// 包含统一导航栏（包含getUserRoles函数）
if (file_exists('common/navigation.php')) {
    require_once 'common/navigation.php';
}

// 权限验证 - 仅考试项目管理员可访问
$user_roles = getUserRoles($current_user_id, $conn);
if (!in_array('考试项目管理员', $user_roles)) {
    ob_end_clean();
    $_SESSION['error_message'] = "访问被拒绝：您需要考试项目管理员权限才能访问此页面";
    header('Location: access_denied.php');
    exit();
}

// 项目进度阶段常量定义
define('PROGRESS_NEW', 1);           // 新建考试项目
define('PROGRESS_ARRANGING', 2);     // 编排考场及预编排监考员
define('PROGRESS_SIGNUP', 3);        // 监考报名
define('PROGRESS_COMPLETED', 4);     // 编排监考员

// 进度描述数组
$progress_descriptions = [
    1 => '新建考试项目',
    2 => '编排考场及预编排监考员',
    3 => '监考报名',
    4 => '编排监考员'
];

// 初始化变量
$success_message = '';
$error_message = '';
$form_data = [
    'exam_name' => '',
    'start_date' => '',
    'end_date' => ''
];

/**
 * 检查表字段是否存在
 */
function columnExists($conn, $table_name, $column_name) {
    try {
        $result = $conn->query("SHOW COLUMNS FROM $table_name LIKE '$column_name'");
        return $result && $result->num_rows > 0;
    } catch (Exception $e) {
        return false;
    }
}

/**
 * 确保必要的字段存在并有默认值
 */
function ensureRequiredColumns($conn) {
    try {
        // 检查并添加end_date字段
        if (!columnExists($conn, 'exams', 'end_date')) {
            $conn->query("ALTER TABLE exams ADD COLUMN end_date DATE COMMENT '项目结束日期'");
        }

        // 检查并添加progress字段
        if (!columnExists($conn, 'exams', 'progress')) {
            $conn->query("ALTER TABLE exams ADD COLUMN progress TINYINT DEFAULT 1 COMMENT '项目进度(1-4)'");
        }

        // 检查并修复subject_count字段（确保有默认值）
        if (!columnExists($conn, 'exams', 'subject_count')) {
            $conn->query("ALTER TABLE exams ADD COLUMN subject_count INT DEFAULT 0 COMMENT '考试科目数量'");
        } else {
            // 字段存在，确保有默认值
            $conn->query("ALTER TABLE exams MODIFY COLUMN subject_count INT DEFAULT 0 COMMENT '考试科目数量'");
        }

        // 检查并修复其他可能缺少默认值的字段
        $required_fields = [
            'students_per_subject' => 'INT DEFAULT 0 COMMENT "每科学生数"',
            'rooms_per_subject' => 'INT DEFAULT 0 COMMENT "每科课室数"',
            'invigilators_per_subject' => 'INT DEFAULT 0 COMMENT "每科监考员数"'
        ];

        foreach ($required_fields as $field => $definition) {
            if (!columnExists($conn, 'exams', $field)) {
                $conn->query("ALTER TABLE exams ADD COLUMN $field $definition");
            } else {
                // 确保现有字段有默认值
                $conn->query("ALTER TABLE exams MODIFY COLUMN $field $definition");
            }
        }

        return true;
    } catch (Exception $e) {
        error_log("添加字段失败: " . $e->getMessage());
        return false;
    }
}

// 确保数据库字段存在并有正确的默认值
ensureRequiredColumns($conn);

// 处理表单提交 - 修复版（使用输出缓冲防止header错误）
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        // 获取表单数据
        $exam_name = trim($_POST['exam_name'] ?? '');
        $start_date = trim($_POST['start_date'] ?? '');
        $end_date = trim($_POST['end_date'] ?? '');

        // 保存表单数据用于回显
        $form_data = [
            'exam_name' => $exam_name,
            'start_date' => $start_date,
            'end_date' => $end_date
        ];

        // 后端验证
        if (empty($exam_name)) {
            throw new Exception('考试项目名称不能为空');
        }

        if (strlen($exam_name) < 2) {
            throw new Exception('考试项目名称至少需要2个字符');
        }

        if (strlen($exam_name) > 100) {
            throw new Exception('考试项目名称不能超过100个字符');
        }

        if (empty($start_date)) {
            throw new Exception('项目开始日期不能为空');
        }

        if (empty($end_date)) {
            throw new Exception('项目结束日期不能为空');
        }

        // 日期格式验证
        if (!DateTime::createFromFormat('Y-m-d', $start_date)) {
            throw new Exception('项目开始日期格式不正确');
        }

        if (!DateTime::createFromFormat('Y-m-d', $end_date)) {
            throw new Exception('项目结束日期格式不正确');
        }

        // 日期逻辑验证
        if (strtotime($end_date) <= strtotime($start_date)) {
            throw new Exception('项目结束日期必须晚于开始日期');
        }

        // 检查开始日期不能是过去的日期
        if (strtotime($start_date) < strtotime(date('Y-m-d'))) {
            throw new Exception('项目开始日期不能早于今天');
        }

        // 检查项目名称是否已存在
        $check_sql = "SELECT id FROM exams WHERE exam_name = ?";
        $check_stmt = $conn->prepare($check_sql);
        if (!$check_stmt) {
            throw new Exception('数据库查询准备失败: ' . $conn->error);
        }

        $check_stmt->bind_param("s", $exam_name);
        $check_stmt->execute();
        $check_result = $check_stmt->get_result();

        if ($check_result->num_rows > 0) {
            $check_stmt->close();
            throw new Exception('该考试项目名称已存在，请使用其他名称');
        }
        $check_stmt->close();

        // 使用正确的mysqli事务处理
        $conn->autocommit(FALSE);

        try {
            // 修复：包含所有必需字段的INSERT语句
            $sql = "INSERT INTO exams (
                exam_name,
                exam_date,
                end_date,
                subject_count,
                students_per_subject,
                rooms_per_subject,
                invigilators_per_subject,
                progress,
                status,
                created_by,
                created_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'active', ?, NOW())";

            $stmt = $conn->prepare($sql);
            if (!$stmt) {
                throw new Exception('数据库语句准备失败: ' . $conn->error);
            }

            // 设置默认值
            $subject_count = 0;              // 默认科目数量为0（新建时暂未设置）
            $students_per_subject = 0;       // 默认每科学生数为0
            $rooms_per_subject = 0;          // 默认每科课室数为0
            $invigilators_per_subject = 0;   // 默认每科监考员数为0
            $progress = PROGRESS_NEW;        // 项目进度为阶段1

            // 修复：确保参数数量和类型完全匹配
            // 9个占位符对应9个参数: sssiiiiis
            $stmt->bind_param("sssiiiiis",
                $exam_name,                  // s - string
                $start_date,                 // s - string
                $end_date,                   // s - string
                $subject_count,              // i - integer
                $students_per_subject,       // i - integer
                $rooms_per_subject,          // i - integer
                $invigilators_per_subject,   // i - integer
                $progress,                   // i - integer
                $current_user_id             // s - string
            );

            if (!$stmt->execute()) {
                throw new Exception('创建项目失败: ' . $stmt->error);
            }

            $new_project_id = $conn->insert_id;
            $stmt->close();

            // 提交事务
            $conn->commit();
            $conn->autocommit(TRUE);

            // 记录操作日志
            error_log("新建考试项目成功: ID={$new_project_id}, 名称={$exam_name}, 创建者={$current_user_id}");

            // 清空输出缓冲区并重定向
            ob_end_clean();
            $_SESSION['success_message'] = "考试项目「{$exam_name}」创建成功！";
            header("Location: exam_projects.php");
            exit();

        } catch (Exception $e) {
            // 回滚事务
            $conn->rollback();
            $conn->autocommit(TRUE);
            throw $e;
        }

    } catch (Exception $e) {
        // 确保自动提交已恢复
        if (isset($conn)) {
            $conn->autocommit(TRUE);
        }

        $error_message = $e->getMessage();
        error_log("创建考试项目失败: " . $error_message . " (用户: {$current_user_id})");
    }
}

$page_title = '新建考试项目 - 考务管理系统';
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($page_title); ?></title>

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <style>
    .main-content {
        margin-top: 20px;
        padding-bottom: 40px;
    }

    .page-header {
        background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
        color: white;
        padding: 30px;
        border-radius: 10px;
        margin-bottom: 20px;
        text-align: center;
        width: 100%;
    }

    .form-container {
        background: white;
        border-radius: 10px;
        box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        padding: 30px;
        max-width: 600px;
        margin: 0 auto;
    }

    .form-label {
        font-weight: 600;
        color: #495057;
        margin-bottom: 8px;
    }

    .form-control {
        border-radius: 8px;
        border: 2px solid #e9ecef;
        padding: 12px 15px;
        font-size: 16px;
        transition: all 0.3s ease;
    }

    .form-control:focus {
        border-color: #28a745;
        box-shadow: 0 0 0 0.2rem rgba(40, 167, 69, 0.25);
    }

    .form-control.is-invalid {
        border-color: #dc3545;
    }

    .form-control.is-valid {
        border-color: #28a745;
    }

    .invalid-feedback {
        display: block;
        font-size: 14px;
        margin-top: 5px;
    }

    .btn-success {
        background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
        border: none;
        border-radius: 8px;
        padding: 12px 30px;
        font-weight: 600;
        font-size: 16px;
        transition: all 0.3s ease;
    }

    .btn-success:hover {
        background: linear-gradient(135deg, #218838 0%, #1e7e34 100%);
        transform: translateY(-2px);
        box-shadow: 0 4px 15px rgba(40, 167, 69, 0.3);
    }

    .btn-secondary {
        border-radius: 8px;
        padding: 12px 30px;
        font-weight: 600;
        font-size: 16px;
    }

    .progress-info {
        background-color: #e7f3ff;
        border: 1px solid #b3d9ff;
        border-radius: 8px;
        padding: 20px;
        margin-bottom: 30px;
    }

    .progress-stages {
        display: flex;
        justify-content: space-between;
        margin-top: 15px;
    }

    .progress-stage {
        text-align: center;
        flex: 1;
        padding: 10px 5px;
        border-radius: 5px;
        margin: 0 2px;
        font-size: 12px;
    }

    .progress-stage.active {
        background-color: #28a745;
        color: white;
        font-weight: bold;
    }

    .progress-stage.inactive {
        background-color: #f8f9fa;
        color: #6c757d;
    }

    .required-field {
        color: #dc3545;
        font-weight: bold;
    }

    @media (max-width: 768px) {
        .form-container {
            margin: 0 15px;
            padding: 20px;
        }

        .progress-stages {
            flex-direction: column;
        }

        .progress-stage {
            margin-bottom: 5px;
        }
    }
    </style>
</head>
<body>
    <!-- 统一导航栏 -->
    <?php
    if (file_exists('common/navigation.php')) {
        include_once 'common/navigation.php';
    } else {
        // 备用导航栏
        echo '<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
                <div class="container">
                    <a class="navbar-brand" href="user_home.php">考务管理系统</a>
                    <div class="navbar-nav ms-auto">
                        <span class="navbar-text me-3">用户: ' . htmlspecialchars($current_user_id) . '</span>
                        <a class="nav-link" href="logout.php">退出登录</a>
                    </div>
                </div>
              </nav>';
    }
    ?>

    <!-- 主要内容 -->
    <div class="container main-content">
        <!-- 页面标题 -->
        <div class="page-header">
            <h1 class="mb-2">
                <i class="fas fa-plus-circle"></i> 新建考试项目
            </h1>
            <p class="mb-0">创建新的考试项目，设置项目基本信息和时间安排</p>
        </div>

        <!-- 项目进度说明 -->
        <div class="progress-info">
            <h5><i class="fas fa-info-circle"></i> 项目进度阶段说明</h5>
            <p class="mb-2">新建的考试项目将按以下4个阶段进行管理：</p>
            <div class="progress-stages">
                <div class="progress-stage active">
                    <div><strong>阶段 1</strong></div>
                    <div>新建考试项目</div>
                </div>
                <div class="progress-stage inactive">
                    <div><strong>阶段 2</strong></div>
                    <div>编排考场及预编排监考员</div>
                </div>
                <div class="progress-stage inactive">
                    <div><strong>阶段 3</strong></div>
                    <div>监考报名</div>
                </div>
                <div class="progress-stage inactive">
                    <div><strong>阶段 4</strong></div>
                    <div>编排监考员</div>
                </div>
            </div>
        </div>

        <!-- 表单容器 -->
        <div class="form-container">
            <!-- 错误消息 -->
            <?php if (!empty($error_message)): ?>
                <div class="alert alert-danger alert-dismissible fade show">
                    <i class="fas fa-exclamation-triangle"></i> <?php echo htmlspecialchars($error_message); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <!-- 创建项目表单 -->
            <form method="POST" action="create_exam_project.php" class="needs-validation" novalidate>
                <!-- 考试项目名称 -->
                <div class="mb-4">
                    <label for="exam_name" class="form-label">
                        <i class="fas fa-clipboard-list"></i> 考试项目名称
                        <span class="required-field">*</span>
                    </label>
                    <input type="text"
                           class="form-control"
                           id="exam_name"
                           name="exam_name"
                           value="<?php echo htmlspecialchars($form_data['exam_name']); ?>"
                           placeholder="例如：2024年春季期末考试"
                           maxlength="100"
                           required>
                    <div class="invalid-feedback">
                        请输入考试项目名称（2-100个字符）
                    </div>
                    <div class="form-text">
                        <i class="fas fa-lightbulb"></i> 建议包含年份、学期和考试类型，便于识别和管理
                    </div>
                </div>

                <!-- 项目开始日期 -->
                <div class="mb-4">
                    <label for="start_date" class="form-label">
                        <i class="fas fa-calendar-plus"></i> 计划的项目开始日期
                        <span class="required-field">*</span>
                    </label>
                    <input type="date"
                           class="form-control"
                           id="start_date"
                           name="start_date"
                           value="<?php echo htmlspecialchars($form_data['start_date']); ?>"
                           min="<?php echo date('Y-m-d'); ?>"
                           required>
                    <div class="invalid-feedback">
                        请选择项目开始日期（不能早于今天）
                    </div>
                    <div class="form-text">
                        <i class="fas fa-info-circle"></i> 项目开始日期通常是第一场考试的日期
                    </div>
                </div>

                <!-- 项目结束日期 -->
                <div class="mb-4">
                    <label for="end_date" class="form-label">
                        <i class="fas fa-calendar-check"></i> 计划的项目结束日期
                        <span class="required-field">*</span>
                    </label>
                    <input type="date"
                           class="form-control"
                           id="end_date"
                           name="end_date"
                           value="<?php echo htmlspecialchars($form_data['end_date']); ?>"
                           min="<?php echo date('Y-m-d'); ?>"
                           required>
                    <div class="invalid-feedback">
                        请选择项目结束日期（必须晚于开始日期）
                    </div>
                    <div class="form-text">
                        <i class="fas fa-info-circle"></i> 项目结束日期通常是最后一场考试的日期
                    </div>
                </div>

                <!-- 提交按钮 -->
                <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                    <a href="exam_projects.php" class="btn btn-secondary me-md-2">
                        <i class="fas fa-arrow-left"></i> 取消
                    </a>
                    <button type="submit" class="btn btn-success">
                        <i class="fas fa-plus"></i> 新建考试项目
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>

    <script>
    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', function() {
        console.log('新建考试项目页面加载完成');

        // 设置默认日期
        const today = new Date();
        const startDateInput = document.getElementById('start_date');
        const endDateInput = document.getElementById('end_date');

        // 如果没有值，设置默认值
        if (!startDateInput.value) {
            const nextWeek = new Date(today);
            nextWeek.setDate(today.getDate() + 7);
            startDateInput.value = nextWeek.toISOString().split('T')[0];
        }

        if (!endDateInput.value) {
            const nextMonth = new Date(today);
            nextMonth.setMonth(today.getMonth() + 1);
            endDateInput.value = nextMonth.toISOString().split('T')[0];
        }

        // 动态更新结束日期的最小值
        startDateInput.addEventListener('change', function() {
            const startDate = new Date(this.value);
            const nextDay = new Date(startDate);
            nextDay.setDate(startDate.getDate() + 1);
            endDateInput.min = nextDay.toISOString().split('T')[0];

            // 如果结束日期早于或等于开始日期，自动调整
            if (endDateInput.value && new Date(endDateInput.value) <= startDate) {
                const suggestedEnd = new Date(startDate);
                suggestedEnd.setDate(startDate.getDate() + 7); // 默认项目持续7天
                endDateInput.value = suggestedEnd.toISOString().split('T')[0];
            }
        });
    });

    // Bootstrap 5表单验证
    (function() {
        'use strict';
        window.addEventListener('load', function() {
            var forms = document.getElementsByClassName('needs-validation');
            var validation = Array.prototype.filter.call(forms, function(form) {
                form.addEventListener('submit', function(event) {
                    var isValid = true;

                    // 获取表单字段
                    var examName = document.getElementById('exam_name').value.trim();
                    var startDate = document.getElementById('start_date').value;
                    var endDate = document.getElementById('end_date').value;

                    // 项目名称验证
                    if (examName.length < 2) {
                        isValid = false;
                        document.getElementById('exam_name').setCustomValidity('项目名称至少需要2个字符');
                    } else {
                        document.getElementById('exam_name').setCustomValidity('');
                    }

                    // 日期验证
                    if (startDate && endDate) {
                        var start = new Date(startDate);
                        var end = new Date(endDate);
                        var today = new Date();
                        today.setHours(0, 0, 0, 0);

                        if (start < today) {
                            isValid = false;
                            document.getElementById('start_date').setCustomValidity('开始日期不能早于今天');
                        } else {
                            document.getElementById('start_date').setCustomValidity('');
                        }

                        if (end <= start) {
                            isValid = false;
                            document.getElementById('end_date').setCustomValidity('结束日期必须晚于开始日期');
                        } else {
                            document.getElementById('end_date').setCustomValidity('');
                        }
                    }

                    if (!isValid || form.checkValidity() === false) {
                        event.preventDefault();
                        event.stopPropagation();
                    }

                    form.classList.add('was-validated');
                }, false);
            });
        }, false);
    })();

    // 实时字符计数
    document.getElementById('exam_name').addEventListener('input', function() {
        const maxLength = 100;
        const currentLength = this.value.length;
        const formText = this.parentNode.querySelector('.form-text');

        if (currentLength > maxLength - 20) {
            formText.innerHTML = `<i class="fas fa-exclamation-triangle"></i> 还可输入 ${maxLength - currentLength} 个字符`;
            formText.style.color = '#dc3545';
        } else {
            formText.innerHTML = '<i class="fas fa-lightbulb"></i> 建议包含年份、学期和考试类型，便于识别和管理';
            formText.style.color = '#6c757d';
        }
    });
    </script>

    <?php
    // 关闭数据库连接
    if (isset($conn) && $conn instanceof mysqli) {
        $conn->close();
    }

    // 结束输出缓冲
    if (ob_get_level()) {
        ob_end_flush();
    }
    ?>
</body>
</html>